package _2022.hot100._84_柱状图中最大的矩形;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author： YHSimon
 * @date： 2022-04-20 15:25
 */
public class Solution {

    //单调栈
    public int largestRectangleArea3(int[] heights){
        int n=heights.length,ans=0;
        int[] left=new int[n];
        int[] right=new int[n];
        Deque<Integer> monoStack=new ArrayDeque<>();
        for(int i=0;i<n;i++){
            while(!monoStack.isEmpty()&&heights[monoStack.peek()]>=heights[i]){
                monoStack.pop();
            }
            left[i]=monoStack.isEmpty()?-1:monoStack.peek();
            monoStack.push(i);
        }

        monoStack.clear();
        for(int i=n-1;i>=0;i--){
            while (!monoStack.isEmpty()&&heights[monoStack.peek()]>=heights[i]){
                monoStack.pop();
            }
            right[i]=monoStack.isEmpty()?n:monoStack.peek();
            monoStack.push(i);
        }

        for(int i=0;i<n;i++){
            ans=Math.max(ans, heights[i]*(right[i]-left[i]-1));
        }
        return ans;
    }

    //枚举 高
    public int largestRectangleArea2(int[] heights){
        int n=heights.length;
        int ans=0;
        //枚举高
        for(int i=0;i<n;i++){
            int left=i,right=i;
            //寻找左边界
            while(left-1>=0&&heights[left-1]>=heights[i]){
                left--;
            }

            while(right+1<n&&heights[right+1]>=heights[i]){
                right++;
            }
            ans=Math.max(ans, heights[i]*(right-left+1));
        }
        return ans;
    }

    //枚举 宽
    public int largestRectangleArea(int[] heights){
        int n=heights.length;
        int ans=0;
        // 枚举左边界
        for(int i=0;i<n;i++){
            int minHeight=heights[i];
            // 枚举右边界
            for(int j=i;j<n;j++){
                minHeight=Math.min(minHeight, heights[j]);
                ans=Math.max(ans, minHeight*(j-i+1));
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        System.out.println(s.largestRectangleArea2(new int[]{2, 1, 5, 6, 2, 3}));
//        System.out.println(s.largestRectangleArea(new int[]{2, 4}));

    }
}
